import type { ProviderDailyRow, SeriesRow } from '../shared/types.js';

export function applyQfq(data: ProviderDailyRow[], factorMap: Map<string, number>): SeriesRow[] {
  if (!data.length) return [];
  const latestDate = data.map(d => d.trade_date).sort((a, b) => b.localeCompare(a))[0];
  const latestFactor = factorMap.get(latestDate);
  if (!latestFactor || isNaN(latestFactor)) return data.map(d => ({ ...d }));
  return data.map((row) => {
    const f = factorMap.get(row.trade_date);
    if (f && !isNaN(f)) {
      const ratio = f / latestFactor;
      const adj = (v: number | undefined) => (v == null || isNaN(Number(v))) ? v as any : Number(v) * ratio;
      return {
        trade_date: row.trade_date,
        open: adj(row.open) as number,
        high: adj(row.high) as number,
        low: adj(row.low) as number,
        close: adj(row.close) as number,
        vol: row.vol,
      };
    }
    return { ...row };
  });
}